package avicit.bdp.dms.oauth2.token;

import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/15 10:27
 */

public class AuthenticationIdGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationIdGenerator.class);

    public AuthenticationIdGenerator() {
    }

    public static String generate(String clientId, String username, String scope) {
        Map<String, String> map = new HashMap();
        map.put("client_id", clientId);
        if (!clientId.equals(username)) {
            map.put("username", username);
        }

        if (!OAuthUtils.isEmpty(scope)) {
            map.put("scope", scope);
        }

        return digest(map);
    }

    protected static String digest(Map<String, String> map) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException var4) {
            LOGGER.warn("Digest error", var4);
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
        }

        try {
            byte[] bytes = digest.digest(map.toString().getBytes("UTF-8"));
            return String.format("%032x", new BigInteger(1, bytes));
        } catch (UnsupportedEncodingException var3) {
            LOGGER.warn("Encoding error", var3);
            throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).");
        }
    }
}
